<template>
  <el-upload v-model:file-list="fileList" :action="url" :headers="uploadHeader" :multiple="props.multiple"
    :limit="props.limit" :on-exceed="handleExceed" :on-error="handleError" :on-success="handleSuccess" ref="uploadRef"
    :accept="props.accept" :before-remove="beforeRemove" :on-remove="handleRemove">
    <el-button>选择文件</el-button>
    <template #tip>
      <div class="el-upload__tip">{{ props.tip }}</div>
    </template>
  </el-upload>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { getToken } from "@/utils/auth";
import { delUploadFile } from "@/api/project/common";
const fileList = defineModel();
const uploadRef = ref();
const uploadHeader = {
  Authorization: "Bearer " + getToken(),
};
const props = defineProps({
  uploadUrl: {
    type: String,
    default: "/commonFile/uploadFile",
  },
  multiple: {
    type: Boolean,
    default: false,
  },
  limit: {
    type: Number,
    default: 10,
  },
  tip: {
    type: String,
    default: "最多可上传10个附件,每个附件大小不超过20M",
  },
  name: {
    type: String,
    default: "file",
  },
  accept: {
    type: String,
    default: "",
  },
  data: {
    type: Object,
    default: () => ({}),
  },
});
//上传地址
const url = computed(() => {
  return import.meta.env.VITE_APP_BASE_API + props.uploadUrl;
});
//文件数量超出限制
const handleExceed = (files, uploadFiles) => {
  ElMessage({
    message: `最多上传${props.limit}个文件！`,
    type: "error",
  });
};
const emit = defineEmits(["change"]);
//删除一个文件
const beforeRemove = (uploadFile, uploadFiles) => {
  //发送请求删除文件
  const id = uploadFile.response ? uploadFile.response.data : uploadFile.id;
  return delFile(id);
};
//文件删除成功
const handleRemove = () => {
  emit("change");
};
//文件上传失败
const handleError = (response) => {
  ElMessage({
    message: `文件上传出错!`,
    type: "error",
  });
};
//文件上传成功
const handleSuccess = (response, UploadFile, uploadFiles) => {
  emit("change");
};
//删除已上传的文件
const delFile = async (id) => {
  try {
    const res = await delUploadFile(id);
    if (res.code == 200) {
      return true;
    } else {
      return false;
    }
  } catch (error) {
    console.log(error);
    return false;
  }
};
</script>

<style scoped lang="scss"></style>
